<template>
  <div class="choose_org_page">
    <!-- 登录选择机构页面 -->
    <div class="header">
      <div class="header_inner">
        <span class="sys_name">日报管理系统</span>
        <el-input
          v-model="filterData.orgName"
          ref="orgNameRef"
          placeholder="机构名称"
          maxlength="50"
          clearable
          class="search_box"
          @keyup.enter="handleSearch"
          @clear="handleSearch"
          @input="debounceSearch"
        >
          <template #prepend>
            <search class="icon" @click="focusInput('orgNameRef')" />
          </template>
        </el-input>
        <el-button-group>
          <el-button type="primary" @click="handleCreate"> 新建 </el-button>
          <el-button type="warning" @click="logout" plain> 退出 </el-button>
        </el-button-group>
        <!-- <el-button type="warning" @click="logout" plain> 退出 </el-button> -->
      </div>
    </div>
    <PageAlert ref="pageAlertRef" />
    <div class="main_content">
      <div class="org_list" v-loading="tableLoading">
        <div v-if="tableData.length" class="list_content">
          <div v-for="(item, i) in tableData" :key="i" class="list_item">
            <div class="item_left_box">
              <div
                class="org_avatar"
                :style="{
                  'background-color':
                    i % 2 ? 'rgb(151, 162, 226)' : 'aquamarine',
                }"
              >
                {{
                  item.orgShortName
                    ? item.orgShortName.slice(0, 1)
                    : item.orgName.slice(0, 1)
                }}
              </div>
            </div>
            <div class="item_middle_box">
              <!-- <div class="org_name">广州市百家医道健康股份有限公司</div> -->
              <div class="org_name">{{ item.orgName }}</div>
              <div class="create_info d_f j_s">
                <span>机构管理者：{{ item.orgManagerName }}</span>
                <span>创建时间：{{ item.createdTime }}</span>
              </div>
            </div>
            <div class="item_right_box">
              <el-button
                v-if="item.orgStatus !== '1'"
                type="danger"
                plain
                disabled
              >
                已被停用
              </el-button>
              <el-button
                v-else-if="item.canJoin === '1'"
                type="success"
                plain
                @click="chooseOrg(item, i)"
              >
                选择加入
              </el-button>
              <el-button
                v-else-if="item.canJoin === '0'"
                type="info"
                plain
                disabled
              >
                不可加入
              </el-button>
            </div>
          </div>
        </div>
        <div v-else style="padding-top: 20vh">
          <el-empty description="暂无数据"></el-empty>
        </div>
      </div>
      <el-pagination
        v-model="pagenationData.current"
        :page-size="pagenationData.size"
        layout="total, prev, pager, next, jumper"
        :total="pagenationData.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        small
        style="text-align: center; margin-top: 10px"
      >
      </el-pagination>
    </div>

    <!-- 新建机构弹框 -->
    <OrgFormDialog
      ref="orgFormDialogRef"
      :prepareData="prepareData"
      :managerVisibel="false"
      :canJoinVisibel="false"
      @updateSuccess="userBindOrg"
    />

    <!-- 机构验证弹框 -->
    <OrgVerifyDialog ref="orgVerifyDialogRef" @verify="handleVerify" />
  </div>
</template>

<script>
import {
  ref,
  reactive,
  getCurrentInstance,
  onMounted,
  toRefs,
  nextTick,
} from "vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox, ElLoading } from "element-plus";
import { debounce } from "lodash";
import PageAlert from "../../components/layout/PageAlert.vue";
import OrgFormDialog from "../organization/components/OrgFormDialog.vue";
import OrgVerifyDialog from "../organization/components/OrgVerifyDialog.vue";

const initFilterData = () => {
  return {
    orgName: "",
    orgStatus: "1",
    canJoin: "1",
  };
};

export default {
  name: "ChooseOrg",
  components: { PageAlert, OrgFormDialog, OrgVerifyDialog },
  setup(props, context) {
    const { proxy } = getCurrentInstance();
    const $api = proxy.$api;
    const router = useRouter();
    const store = useStore();

    const orgNameRef = ref(null);
    const orgFormDialogRef = ref(null);
    const pageAlertRef = ref(null);
    const orgVerifyDialogRef = ref(null);

    const showPageAlert = ({ message, key, type }) => {
      nextTick(() => {
        pageAlertRef.value.show({ message, key, type });
      });
    };

    // 搜索绑定的数据
    const filterData = reactive(initFilterData());

    // 真正的搜索条件
    const condition = reactive({});

    const tableState = reactive({
      tableData: [],
      tableLoading: false,
    });

    // 分页组件
    const pagenationData = reactive({
      current: 1,
      size: 15,
      total: 0,
    });

    // 预加载数据
    const prepareData = reactive({
      orgStatusSelectList: [],
      canJoinSelectList: [],
      isOpenVerificationSelectList: [],
    });

    // 获取列表数据
    const getTableData = () => {
      tableState.tableLoading = true;
      $api.organization
        .listPageChoose({
          ...pagenationData,
          condition,
        })
        .then((res) => {
          tableState.tableLoading = false;
          tableState.tableData = res.data.list;
          pagenationData.total = res.data.total;
          pagenationData.current = res.data.current;
        })
        .catch((err) => {
          tableState.tableLoading = false;
          console.error("tableData error: ", err);
        });
    };

    // 重置
    const handleReset = () => {
      const initData = initFilterData();
      Object.keys(filterData).forEach((key) => {
        filterData[key] = initData[key];
      });
      pagenationData.current = 1;
      handleSearch();
    };

    // 搜索
    const handleSearch = () => {
      Object.keys(filterData).forEach((key) => {
        // 解决后端枚举类型传空字符串解析报错的问题
        condition[key] = filterData[key] === "" ? null : filterData[key];
      });
      pagenationData.current = 1;
      getTableData();
    };

    // 新建
    const handleCreate = () => {
      orgFormDialogRef.value && orgFormDialogRef.value.open();
    };

    // 分页-切换页大小
    const handleSizeChange = (size) => {
      pagenationData.size = size;
      getTableData();
    };

    // 分页-切换页数
    const handleCurrentChange = (current) => {
      pagenationData.current = current;
      getTableData();
    };

    // 选择机构
    const chooseOrg = (item, index) => {
      // 判断是否开启验证
      if (item.isOpenVerification === "1") {
        orgVerifyDialogRef.value && orgVerifyDialogRef.value.open(item);
        return;
      }
      ElMessageBox.confirm(`确定选择加入【${item.orgName}】吗？`, "提示", {
        type: "warning",
      })
        .then(() => {
          userBindOrg(item.id, null);
        })
        .catch(() => {});
    };

    // 当前登录用户绑定机构接口
    const userBindOrg = (orgId, verifyAnswer) => {
      tableState.tableLoading = true;
      $api.users
        .userBindOrg({
          orgId,
          verifyAnswer,
        })
        .then((res) => {
          orgVerifyDialogRef.value && orgVerifyDialogRef.value.close();
          ElMessage.success("关联机构成功！");
          store.commit("user/setUserInfo", res.data);
          router.replace("/");
        })
        .catch((err) => {
          console.error("userBindOrg error: ", err);
        })
        .finally(() => {
          tableState.tableLoading = false;
        });
    };

    // 退出
    const logout = (item, index) => {
      ElMessageBox.confirm(`确定要退出登录吗？`, "提示", { type: "warning" })
        .then(() => {
          userLogout();
        })
        .catch(() => {});
    };

    // 退出登录
    const userLogout = () => {
      const loading = ElLoading.service({
        lock: true,
        text: "Loading",
        background: "rgba(255, 255, 255, 0.5)",
      });
      $api.users
        .logout({})
        .then((res) => {})
        .catch((err) => {
          console.error("userLogout error: ", err);
        })
        .finally(() => {
          loading.close();
          store.commit("user/logout");
        });
    };

    // 查询预加载数据
    const getPreparedData = () => {
      $api.organization
        .preparedData()
        .then((res) => {
          Object.keys(prepareData).forEach((key) => {
            prepareData[key] = res.data[key] || [];
          });
        })
        .catch((err) => {
          console.error("getPreparedData error: ", err);
        })
        .finally(() => {});
    };

    // 验证问题
    const handleVerify = ({ id, verifyAnswer }) => {
      userBindOrg(id, verifyAnswer);
    };

    // 输入框聚焦
    const focusInput = (refKey) => {
      switch (refKey) {
        case "orgNameRef":
          orgNameRef.value && orgNameRef.value.focus();
          break;
      }
    };

    // 防抖
    const debounceSearch = debounce(handleSearch, 800);

    /**
     * 初始化
     */
    showPageAlert({
      message: "亲，您还没有加入机构，请选择创建或者加入机构",
      key: "ChooseOrg",
      type: "warning",
    });

    getPreparedData();

    onMounted(() => {
      handleSearch();
    });

    return {
      filterData,
      pagenationData,
      orgNameRef,
      pageAlertRef,
      orgVerifyDialogRef,
      orgFormDialogRef,
      handleSizeChange,
      handleCurrentChange,
      handleReset,
      handleCreate,
      handleSearch,
      chooseOrg,
      logout,
      debounceSearch,
      focusInput,
      userBindOrg,
      prepareData,
      handleVerify,
      ...toRefs(tableState),
    };
  },
};
</script>

<style lang="less" scoped>
.choose_org_page {
  background: #f7f9fc;
  padding-top: 56px;
  height: 100vh;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;

  .header {
    background: #fff;
    height: 56px;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    width: 100%;
    z-index: 10;
    box-shadow: 4px -4px 10px rgba(0, 0, 0, 0.3);
    .header_inner {
      width: 1000px;
      height: 100%;
      margin: 0 auto;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .sys_name {
      font-size: 18px;
      font-weight: 600;
      color: #999;
    }
    .search_box {
      width: 300px;
    }
  }

  .main_content {
    padding-bottom: 15px;
    flex: 1;
    overflow: hidden;
    display: flex;
    flex-direction: column;
  }

  .org_list {
    flex: 1;
    overflow: hidden auto;
    .list_content {
      padding-top: 20px;
      .list_item {
        width: 1000px;
        margin: 0 auto;
        background: #fff;
        border-radius: 4px;
        margin-bottom: 20px;
        display: flex;
        align-items: center;
        padding: 0 20px;
        // cursor: pointer;
        &:hover {
          box-shadow: 4px 2px 10px rgba(0, 0, 0, 0.1);
          background: #f5f9ff;
        }
        .item_left_box {
          padding: 20px 0;
          margin-right: 20px;
        }
        .item_middle_box {
          padding: 15px 0;
          flex: 1;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
        }
        .item_right_box {
          margin-left: 20px;
        }
        .org_avatar {
          width: 80px;
          height: 80px;
          line-height: 80px;
          border-radius: 4px;
          background-color: aquamarine;
          color: #fff;
          font-size: 40px;
          text-align: center;
        }
        .org_name {
          font-size: 22px;
          color: #222;
          // line-height: 30px;
          margin-bottom: 10px;
          font-weight: bold;
        }
        .create_info {
          color: #999;
        }
      }
    }
  }
}
</style>
